package com.wrx.club_management_backend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wrx.club_management_backend.common.AjaxResult;
import com.wrx.club_management_backend.dto.*;
import com.wrx.club_management_backend.entity.User;
import com.wrx.club_management_backend.service.MsgService;
import com.wrx.club_management_backend.service.UserService;
import com.wrx.club_management_backend.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.json.AbstractJackson2Decoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    MsgService msgService;


    @PostMapping("/register")
    public AjaxResult register(@RequestBody User user){
        return userService.register(user);
    }

    @GetMapping("/num")
    public AjaxResult num(){
        return userService.num();
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody User user, HttpServletRequest request){
        // 如果 user中不为空的数据就更新，为空的数据就不动
        String token = request.getHeader("Authorization");
        userService.updateUser(user,token);
        return AjaxResult.success("更新成功");
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginFormDTO loginFormDTO){
        return userService.login(loginFormDTO);
    }

    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        return userService.logout(request);
    }

    /**
     * 获取当前登录用户的信息
     * @return
     */
    @PostMapping("/info")
    public AjaxResult info(){
        return AjaxResult.success(UserHolder.getUser());
    }

    @PostMapping("/detail")
    public AjaxResult detail(){
        return userService.detail();
    }


    @GetMapping("/search")
    public AjaxResult searchUsers(@RequestParam(required = false) String keyword,
                                  @RequestParam(required = false) String searchMode) {
        log.warn("keyword = {} searchMode = {}", keyword, searchMode);
        List<User> users = userService.searchUsers(keyword, searchMode);
        return AjaxResult.success(users);
    }

    /**
     * 列出好友列表
     * @return 好友列表
     */
    @GetMapping("/friends")
    public AjaxResult friends(){
        return userService.friends();
    }

    /**
     * 添加好友
     * @param id 要有id
     * @return
     */
    @PostMapping("/addfriend/{userId}")
    public AjaxResult addFriend( @PathVariable("userId") Long id){
        return  userService.addFriend(id);
    }

    /**
     * 删除好友
     * @param userId
     * @return
     */
    @PostMapping("/removeFriend/{userId}")
    public AjaxResult removeFriend(@PathVariable("userId") Long userId){
        return userService.removeFriend(userId);
    }

    /**
     * 发送消息
     * @param dto
     * @return
     */
    @PostMapping("/send")
    public AjaxResult send(@RequestBody MsgDTO dto){
        return msgService.send(dto);
    }


    @PostMapping("/detail/{userId}")
    public AjaxResult detail( @PathVariable("userId")Long userId){
        User byId = userService.getById(userId);
        UserDTO dto = new UserDTO();
        BeanUtil.copyProperties(byId, dto, true);
        return AjaxResult.success(dto);
    }

    @PostMapping("getDetailByPhone/{phone}")
    public AjaxResult getDetailByPhone(@PathVariable("phone") String phone){
        User one = userService.getOne(
                new LambdaUpdateWrapper<User>()
                        .eq(User::getSno, phone)
        );
        if(one == null) return AjaxResult.error("用户不存在");
        return AjaxResult.success(one);
    }

    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody PasswordUpdateDTO passwordUpdateDTO) {
        // 从当前会话获取用户ID
        Long userId = UserHolder.getUser().getId();

        try {
            boolean success = userService.updatePassword(userId,
                    passwordUpdateDTO.getOldPassword(),
                    passwordUpdateDTO.getNewPassword());
            if (success) {
                return AjaxResult.success("密码修改成功");
            } else {
                return AjaxResult.error("旧密码验证失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("密码修改失败：" + e.getMessage());
        }
    }

    @PostMapping("/search")
    public  AjaxResult search(@RequestBody UserSearchDTO dto){
        return this.userService.search(dto);
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @PostMapping("/del/{userId}")
    public AjaxResult delUser(@PathVariable("userId") Long userId){
        return userService.delUser(userId);
    }






}
